<script setup>
import {ref, computed, onMounted} from "vue";
import SidebarItem from "./SidebarItem.vue";
import { Fold, Expand } from "@element-plus/icons-vue";
import { useRoute } from "vue-router";
import {userStore} from "@/store/index.js";
import axios from "axios";

const route = useRoute();
const isCollapse = ref(false);

const store = userStore()
const userItemStore = userStore()
userItemStore.user
userItemStore.loggedIn
// 路由菜单配置
const routes = ref([
  {
    path: "/dashboard",
    name: "Dashboard",
    meta: { title: "首页", icon: "House" },
  },
  {
    path: "/store",
    name: "Store",
    meta: { title: "门店", icon: "Shop" },
    children: [
      { path: "manage", name: "StoreManage", meta: { title: "门店管理" } },
      {
        path: "staff",
        name: "StaffManage",
        meta: { title: "员工管理" },
        // 添加子路由
        children: [
          {
            path: "list",
            name: "StaffList",
            meta: { title: "员工列表" },
            component: () => import("../views/store/EmployeeList.vue"), // 懒加载组件
          },
          {
            path: 'schedule',
            name: 'StaffSchedule',
            meta: { title: '员工排班' },
            component: () => import('../views/store/StaffManage.vue')
          },
          {
            path: 'loginInfo',
            name: 'loginInfo',
            meta: { title: '员工登录信息' },
            component: () => import('../views/store/loginInfo.vue')
          }
        ]
      },
      {
        path: 'table', name: 'TableManage', meta: {title: '台桌管理'},
        children: [
          {path: 'Alterable', name: 'TableType', meta: {title: '桌子一览'}},
          {path: 'type', name: 'TableType', meta: {title: '桌型管理'}},
          {path: 'create', name: 'TableCreate', meta: {title: '新建台桌'}},
          {path: 'booking', name: 'TableBooking', meta: {title: '预订设置'}}
        ]
      },
      {path: 'device', name: 'DeviceManage', meta: {title: '硬件管理'}}
    ]
  },
  {path: 'receipt', name: 'ReceiptManage', meta: {title: '小票管理', icon: 'Document'},
    children: [
      {path: 'dine-in', name: 'DineInReceipt', meta: {title: '堂食小票'}},
      {path: 'take-out', name: 'TakeOutReceipt', meta: {title: '外卖小票'}},
      {path: 'recharge', name: 'RechargeReceipt', meta: {title: '充值小票'}},
    ]
  },
  {
    path: "/business",
    name: "Business",
    meta: { title: "业务", icon: "Menu" },
    children: [
      {
        path: "dishManger",
        name: "Dish",
        meta: { title: "菜品管理" },
        children: [
          { path: "dish", name: "Dish", meta: { title: "菜品" } },
          {
            path: "dish_category",
            name: "DishCategory",
            meta: { title: "分类" },
          },
          { path: "flavor", name: "Flavor", meta: { title: "口味" } },
          { path: "spec", name: "SpcManage", meta: { title: "规格" } },
          {
            path: "material_category",
            name: "MaterialCategory",
            meta: { title: "原料类别" },
          },
          { path: "ingredient", name: "Ingredient", meta: { title: "原料" } },
        ],
      },

      { path: "DineInManage", name: "DineInManage", meta: { title: "堂食" } },
      { path: "TakeOutManage", name: "TakeOutManage", meta: { title: "外卖" } },
      {
        path: "DeliverySetting",
        name: "DeliverySetting",
        meta: { title: "配送" },
      },
    ],
  },
  {
    path: "/inventory",
    name: "Inventory",
    meta: { title: "库存", icon: "Box" },
    children: [
      { path: "dishes", name: "DishesInventory", meta: { title: "菜品库" } },
      {
        path: "materials",
        name: "MaterialsInventory",
        meta: { title: "原料库" },
      },
      { path: "check", name: "InventoryCheck", meta: { title: "库存盘点库" } },
    ],
  },
  {
    path: "/order",
    name: "Order",
    meta: { title: "订单", icon: "Tickets" },
    children: [
      { path: "indent", name: "Sit-downOrder", meta: { title: "堂食订单" } },
      {
        path: "TakeoutOrder",
        name: "TakeoutOrder",
        meta: { title: "外卖订单" },
      },
      {
        path: "AdvanceOrder",
        name: "AdvanceOrder",
        meta: { title: "餐桌预约订单" },
      },
    ],
  },
  {
    path: "/member",
    name: "Member",
    meta: { title: "会员", icon: "User" },
    children: [
      { path: "vip", name: "Vip", meta: { title: "会员管理" } },
      { path: "vipType", name: "VipType", meta: { title: "会员类别" } },
    ],
      {path: 'CouponList', name: 'CouponList', meta: {title: '促销券'}},
      // {path:'CouponDetailsPage' ,name:'CouponDetailsPage',meta: {title: '优惠券详情'}}
    ]
  },
  {
    path: "/promotion",
    name: "Promotion",
    meta: { title: "促销", icon: "Discount" },
    children: [
      { path: "coupon", name: "PromotionCoupon", meta: { title: "促销券" } },
    ],
  },
  {
    path: "/report",
    name: "Report",
    meta: { title: "报表", icon: "DataAnalysis" },
    children: [
      { path: "dishes-flow", name: "DishesFlow", meta: { title: "菜品流水" } },
      { path: "payment", name: "PaymentReport", meta: { title: "收款报表" } },
      {
        path: "dishes-rank",
        name: "DishesRank",
        meta: { title: "菜品销量排行" },
      },
      { path: "refund", name: "RefundRecord", meta: { title: "退单记录" } },
      {
        path: "store-sales",
        name: "StoreSalesRank",
        meta: { title: "门店销售排行" },
      },
    ],
  },
  {
    path: "/setting",
    name: "Setting",
    meta: { title: "设置", icon: "Setting" },
    children: [
      { path: "payment", name: "PaymentSetting", meta: { title: "支付设置" } },
      { path: "account", name: "AccountSetting", meta: { title: "账号设置" } },
    ],
  },
]);

// 当前激活菜单
const activeMenu = computed(() => {
  const { meta, path } = route;
  if (meta.activeMenu) {
    return meta.activeMenu;
  }
  return path;
});
// 退出登录
const quit =()=>{
  axios.get(`/user/clearToken/${store.user.id}`).then(res=>{
    console.log(res.data);
  })
  // 情况sessionStorage
  sessionStorage.removeItem("user");
  // 跳转
  location.href="/login";
}
// 获取权限
const fetchPermissions = async (userId) => {
  try {
    const response = await axios.get(`/permissions/getPermissionsByUserId/${userId}`);
    // 假设后端返回的权限数据存储在 response.data 中
    store.permissions = response.data.obj;
    console.log(store.permissions);
  } catch (error) {
    console.error('Failed to fetch permissions:', error);
  }
};
onMounted(()=>{
 if(userItemStore.loggedIn == false){
   router.push("/login");
 }else{
   userItemStore.setUser(userItemStore.user)
   console.log(userItemStore.user)
 }
  console.log(userItemStore.user)
  if (userItemStore.user && userItemStore.user.id) {
    fetchPermissions(userItemStore.user.id);
  }
})
</script>
<template>
  <div class="app-container">
    <!-- 左侧菜单 -->
    <div class="sidebar-container">
      <div class="logo-container">
        <h1>智慧餐厅</h1>
      </div>
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        unique-opened
        router
      >
        <sidebar-item v-for="route in routes" :key="route.path" :item="route" />
      </el-menu>
    </div>

    <!-- 右侧内容区 -->
    <div class="main-container">
      <!-- 顶部导航栏 -->
      <div class="navbar">
        <!-- 折叠按钮 -->
        <div class="hamburger-container" @click="isCollapse = !isCollapse">
          <el-icon :size="20">
            <component :is="isCollapse ? Expand : Fold" />
          </el-icon>
        </div>

        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/" class="breadcrumb-container">
          <el-breadcrumb-item
            v-for="item in route.matched.filter((i) => i.meta?.title)"
            :key="item.path"
          >
            {{ item.meta.title }}
          </el-breadcrumb-item>
        </el-breadcrumb>

        <div class="right-menu">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              <el-avatar
                :size="30"
                src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
              />
              <span class="welcome">欢迎您：{{userItemStore.user ? userItemStore.user.username : ''}}</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>个人中心</el-dropdown-item>
                <el-dropdown-item @click="quit">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 内容区 -->
      <div class="app-main">
        <router-view />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.sidebar-container {
  width: 210px;
  height: 100%;
  background-color: #304156;
  transition: width 0.28s;
  flex-shrink: 0;
  overflow: hidden;

  .logo-container {
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #2b2f3a;

    h1 {
      color: #fff;
      font-size: 18px;
      margin: 0;
    }
  }

  .el-menu {
    border-right: none;
    height: calc(100% - 50px);
  }
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .navbar {
    height: 50px;
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
    display: flex;
    align-items: center;
    padding: 0 15px;

    .hamburger-container {
      line-height: 46px;
      height: 100%;
      cursor: pointer;
    }

    .breadcrumb-container {
      flex: 1;
      padding-left: 10px;
    }

    .right-menu {
      display: flex;
      align-items: center;

      .el-dropdown-link {
        display: flex;
        align-items: center;
        cursor: pointer;

        .user-name {
          margin-left: 8px;
          font-size: 14px;
        }
      }
    }
  }

  .app-main {
    flex: 1;
    padding: 20px;
    overflow: auto;
    background-color: #f0f2f5;
  }
}
</style>
